package cn.com.blueInfo.utils.util;

/**
 * 身份证校验规则
 */
public class IDCardValidator {

    // 加权因子
    private static final int[] WEIGHTS = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    // 校验码对应值
    private static final char[] CHECK_CODES = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};

    /**
     * 验证身份证号码的校验码
     * @param idCard 身份证号码
     * @return 校验结果，true 表示校验通过，false 表示校验失败
     */
    public static boolean validateIdCard(String idCard) {
        if (idCard == null || idCard.length() != 18) {
            return false;
        }
        char[] idChars = idCard.toCharArray();
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            if (!Character.isDigit(idChars[i])) {
                return false;
            }
            sum += (idChars[i] - '0') * WEIGHTS[i];
        }
        int index = sum % 11;
        char expectedCheckCode = CHECK_CODES[index];
        char actualCheckCode = idChars[17];
        return expectedCheckCode == actualCheckCode;
    }

    public static void main(String[] args) {
        String idCard = "13102519900210243X"; // 替换为实际要验证的身份证号
        boolean isValid = validateIdCard(idCard);
        System.out.println("身份证号校验结果: " + (isValid ? "有效" : "无效"));
    }
}
